﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using UnitTestUtils.DB.EF;

namespace UnitTestUtilsTests.DB.EF
{
    [TestFixture]
    public class TestConnectionFactoryTests
    {

        [Test]
        public void FactoryCleansupTheConnectionsItHasCreated()
        {
            var target = new TestConnectionFactory();

            var c1 = target.CreateConnection("");
            var c2 = target.CreateConnection("");

            bool c1Disposed = false;
            c1.Disposed += (s, a) => c1Disposed = true;

            bool c2Disposed = false;
            c2.Disposed += (s, a) => c2Disposed = true;
            
            target.Dispose();

            Assert.IsTrue(c1Disposed);
            Assert.IsTrue(c2Disposed);

            var currentDirectory = Directory.GetCurrentDirectory();
            var files = Directory.GetFiles(currentDirectory, "*.sdf");

            Assert.AreEqual(0, files.Length);
        }

        [Test]
        public void FactoryCleansupTheDBFilesItHasCreated()
        {
            var target = new TestConnectionFactory();

            var c1 = target.CreateConnection("");
            var c2 = target.CreateConnection("");

            var dbContext1 = new DbContext(c1, false);
            dbContext1.Database.CreateIfNotExists();

            var dbContext2 = new DbContext(c2, false);
            dbContext2.Database.CreateIfNotExists();

            bool c1Disposed = false;
            c1.Disposed += (s, a) => c1Disposed = true;

            bool c2Disposed = false;
            c2.Disposed += (s, a) => c2Disposed = true;

            target.Dispose();

            Assert.IsTrue(c1Disposed);
            Assert.IsTrue(c2Disposed);

            var currentDirectory = Directory.GetCurrentDirectory();
            var files = Directory.GetFiles(currentDirectory, "*.sdf");

            Assert.AreEqual(0, files.Length);
        }

        [Test]
        public void ReuseConnectionWhenCalledOnSameThread()
        {
            var fac = new TestConnectionFactory();

            try
            {
                var con1 = fac.CreateConnectionEFConnection("TestModelContainer");
                var con2 = fac.CreateConnectionEFConnection("TestModelContainer");

                Assert.AreEqual(con1, con2);
            }
            finally
            {
                fac.Dispose();
            }
        }
    }
}
